from flask import Flask
from flask_cors import CORS
from flask_redis import FlaskRedis
from Model import models
from conf import redis_url, token_pool, amap_key_route, fire_admin_route, accessKeyId, accessKeySecret, endpoint, bucket
from View import user, travel, caregiver, eldly, nursingnews


def create_app():
    app = Flask(__name__)

    # Initialize Redis
    FlaskRedis(app)

    # Setup CORS
    CORS(app, supports_credentials=True)

    # Application Configuration
    app.config['REDIS_URL'] = redis_url
    app.config['TOKEN_POOL'] = token_pool
    app.config['AMAP_KEY_ROUTE'] = amap_key_route
    app.config['FIRE_ADMIN_ROUTE'] = fire_admin_route
    app.config['ACCESS_KEY_ID'] = accessKeyId
    app.config['ACCESS_KEY_SECRET'] = accessKeySecret
    app.config['END_POINT'] = endpoint
    app.config['BUCKET'] = bucket
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_ECHO'] = True
    app.config.update(RESTFUL_JSON=dict(ensure_ascii=False))
    app.config["JSON_AS_ASCII"] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = models.connect()

    # Initialize SQLAlchemy with the app
    models.db.init_app(app)

    # Register Blueprints
    app.register_blueprint(travel.travel_planner_blue)
    app.register_blueprint(user.user_blue)
    app.register_blueprint(caregiver.caregiver_blue)
    app.register_blueprint(eldly.eldly_blue)
    app.register_blueprint(nursingnews.nursing_news_blue)

    with app.app_context():
        models.db.create_all()  # Create all tables if they don't exist

    return app


if __name__ == '__main__':
    app = create_app()
    app.run(debug=True)
